<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="5">
        <el-col :span="10">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              clearable
              v-model="queryInfo.query"
              @change="getUsersList"
              @keyup.enter.native="getUsersList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户模板 -->
      <el-table stripe :data="userList" border style="width: 100%">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatuChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 修改 -->

            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="updateUserData(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUserData(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="bottom"
            >
              <el-button
                @click="setRolesDialogVisible(scope.row)"
                type="warning"
                size="mini"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <!-- 添加用户的对话框 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="handleClose">
        <!-- 内容主题区域 -->
        <el-form
          :model="addUserList"
          :rules="rules"
          ref="ruleForm"
          label-width="70px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserList.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserList.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserList.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserList.mobile"></el-input>
          </el-form-item>
          <el-form-item class="footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUserData">确 定</el-button>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
      </el-dialog>
      <!-- 修改用户的弹出层 -->
      <el-dialog title="提示" :visible.sync="updateUserVisible" width="50%" @close="editUpdateUser">
        <el-form
          :model="updateUserList"
          :rules="rules"
          ref="updateRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input disabled v-model="updateUserList.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="updateUserList.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="updateUserList.mobile"></el-input>
          </el-form-item>
          <el-form-item class="footer">
            <el-button @click="updateUserVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateData">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 分配角色的弹出层 -->
      <el-dialog
        title="提示"
        :visible.sync="rolesDialogVisible"
        width="50%"
        @close="rolesDialogClosed"
      >
        <div>
          <p>用户姓名为：{{userInfo.username}}</p>
          <p>用户角色为：{{userInfo.role_name}}</p>
          <p>
            选择角色：
            <el-select v-model="selectedRolesId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
import { truncate, truncateSync } from "fs";
export default {
  data() {
    // 验证邮箱的校验规则
    var checkEmile = (rule, val, call) => {
      const regEmi = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (regEmi.test(val)) return call();
      call(new Error("请输入合法的邮箱"));
    };
    // 验证手机号的校验规则
    var checkTel = (rule, val, call) => {
      const regTel = /^([1][3,4,5,6,7,8,9])\d{9}$/;
      if (regTel.test(val)) return call();
      call(new Error("请输入合法的手机号"));
    };
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      //  控制添加框的显示与隐藏
      dialogVisible: false,
      // 添加用户数据
      addUserList: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加用户数据验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 15, message: "长度在 5 到 15 个字符", trigger: "blur" }
        ],
        email: [{ required: true, validator: checkEmile, trigger: "blur" }],
        mobile: [{ required: true, validator: checkTel, trigger: "blur" }]
      },
      // 控制修改用户的显示与隐藏
      updateUserVisible: false,
      // 更新用户列表
      updateUserList: {},
      // 控制分配角色的显示与隐藏
      rolesDialogVisible: false,
      // 当前用户信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRolesId: null,
      userId: null
    };
  },
  methods: {
    async getUsersList() {
      // console.log(v)
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      if (res.meta.status !== 200) return this.$message(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
      // console.log(res)
    },
    handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getUsersList();
    },
    async userStatuChanged(data) {
      // console.log(data)
      const { data: res } = await this.$http.put(
        "users/" + data.id + "/state/" + data.mg_state
      );
      if (res.meta.status !== 200) {
        data.mg_state = !data.mg_state;
        return this.$message.error(res.meta.msg);
      }
      return this.$message.success(res.meta.msg);
    },
    addUserData() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return this.$message.error("请补全信息");
        const { data: res } = await this.$http.post("users", this.addUserList);
        if (res.meta.status != 201) return this.$message.error(res.meta.msg);
        this.dialogVisible = false;
        this.$message.success(res.meta.msg);
        this.getUsersList();
      });
    },
    handleClose() {
      this.$refs.ruleForm.resetFields();
    },
    async updateUserData(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.updateUserList = res.data;
      this.updateUserVisible = true;
    },
    updateData() {
      this.$refs.updateRuleForm.validate(async valid => {
        if (!valid) return this.$message.error("请输入合法内容");
        const { data: res } = await this.$http.put(
          "users/" + this.updateUserList.id,
          {
            email: this.updateUserList.email,
            mobile: this.updateUserList.mobile
          }
        );
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.updateUserVisible = false;
        this.getUsersList();
      });
    },
    async deleteUserData(id) {
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (res !== "confirm") return this.$message.info("已取消删除");
      const { data: result } = await this.$http.delete("users/" + id);
      if (result.meta.status !== 200)
        return this.$message.error(result.meta.msg);
      this.$message.success(result.meta.msg);
      this.deleteUserVisible = false;
      this.getUsersList();
    },
    editUpdateUser() {
      this.$refs.updateRuleForm.resetFields();
    },
    async setRolesDialogVisible(userInfo) {
      // console.log(userInfo);
      this.userInfo = userInfo;
      this.userId = userInfo.id;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesList = res.data;
      // console.log(this.rolesList);
      this.rolesDialogVisible = true;
    },
    // 点击按钮分配角色
    async saveRoleInfo() {
      if (!this.selectedRolesId)
        return this.$message.error("请选择要分配的角色");
      const { data: res } = await this.$http.put(
        "users/" + this.userId + "/role",
        { rid: this.selectedRolesId }
      );
      // console.table(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.rolesDialogVisible = false;
      this.getUsersList();
    },
    rolesDialogClosed() {
      this.selectedRolesId = "";
      this.rolesDialogVisible = false;
    }
  },
  created() {
    this.getUsersList();
  }
};
</script>


<style lang="less" scoped>
.footer {
  text-align: right;
}
</style>
